package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Map;

@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo findById(Long id) {
        return userInfoMapper.selectById(id);
    }

    /**
     * 批量查询数据
     * @param userIds
     * @param userInfo
     * @return
     */
    @Override
    public Map<Long, UserInfo> findByIds(List<Long> userIds, UserInfo userInfo) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        //1.用户id列表
        wrapper.in("id",userIds);
        //userInfo对象主要是用来构造查询的条件，如果不为空就证明有查询条件，添加筛选条件 以年龄和性别为例
        if (userInfo!=null){
            if (userInfo.getAge()!=null){
                wrapper.le("age",userInfo.getAge());
            }
            if (!StringUtils.isEmpty(userInfo.getGender())){
                wrapper.eq("gender",userInfo.getGender());
            }
            if (!StringUtils.isEmpty(userInfo.getNickname())){
                wrapper.like("nickname",userInfo.getNickname());
            }
        }
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        //利用collUtil工具类将list集合转为map集合
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(userInfos, "id");
        return map;
    }

    /**
     * 分页查询全部数据
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public IPage findAll(Integer page, Integer pagesize) {
        Page<UserInfo> page1 = new Page<>(page,pagesize);
        return userInfoMapper.selectPage(page1,null);
    }
}
